'use strict'

const Service = require('egg').Service

class RechargeService extends Service {

    /**
     * 新建接口service
     * @param param
     * @returns {Promise<*>}
     */
    async create(param){
        const {app,ctx,service} = this;
        //引入uuid生成器
        var uuid = require('node-uuid');

        //开启事务
        let t = await ctx.model.transaction();
        try {
            //定义新增的对象
            let recharge = {
                id:uuid.v1(),
                username:param.username,
                money:param.money,
                created_by:await ctx.session.user_info.id,
            };
            console.info(recharge);
            //调用sequelize新增对象 findOrCreate 将返回一个数组[对象，新增成功与否的布尔] 如果新增对象已存在，则返回该对象和false 否则返回新增对象和true
            let rs = await ctx.model.FdRecharge.create(recharge,{transaction:t});

            await ctx.helper.sendQueueMsg('recharge',{username:param.username,money:param.money});

            //提交事务
            t.commit();

            //返回新增结果
            return 'success';

        }catch (e) {
            //若出错 回滚
            t.rollback();
            //抛出出错信息
            ctx.throw(500,e.message)
        }
    }

    async recharge(username,money){
        const {app,ctx,service} = this;
        //开启事务
        let t = await ctx.model.transaction();
        try {
            let rs = await ctx.model.FdUser.findOne({where: {username: username, type: '3'},transaction:t,lock:t.LOCK.UPDATE});

            rs.money = parseFloat(rs.money) + parseFloat(money);

            await rs.save({transaction:t});
            t.commit();
        }catch (e) {
            //失败回滚
            t.rollback();
            //抛出错误信息
            ctx.throw(500,e.message)
        }
        return true;
    }

    async rechargeById(id,money){
        const {app,ctx,service} = this;
        //开启事务
        let t = await ctx.model.transaction();
        try {
            let rs = await ctx.model.FdUser.findOne({where: {id: id},transaction:t,lock:t.LOCK.UPDATE});

            rs.money = parseFloat(rs.money) + parseFloat(money);

            await rs.save({transaction:t});
            t.commit();
        }catch (e) {
            //失败回滚
            t.rollback();
            //抛出错误信息
            ctx.throw(500,e.message)
        }
        return true;
    }
}

module.exports = RechargeService
